// import {
//   asyncRouterMap
// } from '@/router'
import Vue from 'vue'

/**
 * 
 * @param {*} router 
 * @param {*} authInfo 
 */
function checkAuth(router, authInfo) {
  // 判断当前路由在权限数组中是否存在
  if (router.meta) {
    const metaInfo = router.meta
    if (!metaInfo.requiresAuth) {
      return true
    } else {
      //判断菜单code
      if (metaInfo.code) {
        return authInfo.find(i => i.code == metaInfo.code) ? true : false
      } else {
        return true
      }
    }
  }
  return true
}

/**
 * 
 * @param {*} routers 
 * @param {*} authInfo 
 */
const filterAsyncRouter = function (routers, authInfo) {
  const res = []
  routers.forEach(router => {
    const tmp = {
      ...router
    }
    if (checkAuth(tmp, authInfo)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, authInfo)
      }
      res.push(tmp)
    }
  })
  return res
}

const permission = {
  state: {
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      // for (let index = 0; index < routers.length; index++) {
      //   const element = routers[index]
      //   if (element.name == 'crm') {
      //     state.crmRouters = element
      //   } else if (element.name == 'bi') {
      //     state.biRouters = element
      //   } else if (element.name == 'manager') {
      //     state.manageRouters = element
      //   }
      // }
    },
  },
  actions: {
    GenerateRoutes({
      commit
    }, authData) {
      return new Promise(resolve => {
        const accessedRouters = filterAsyncRouter(asyncRouterMap, authData)
        for (let index = 0; index < accessedRouters.length; index++) {
          let element = accessedRouters[index]
          if (element.children && element.children.length > 0) {
            let str = element.children[0].path.startsWith("/") ? "" : "/"
            element.children.push({
              path: "/",
              redirect: str + element.children[0].path
            })
            for (let indexChild = 0; indexChild < element.children.length; indexChild++) {
              //如何路由子集里还有子集，目前处理到第三层
              let elementChild = element.children[indexChild]
              if (elementChild.children && elementChild.children.length > 0) {
                elementChild.children.push({
                  path: "/",
                  redirect: elementChild.children[indexChild].path
                })
              }
            }
          }
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
